/**
 * 司机信息
 */
var iFrameName = this.name;
$(function(){
	Vehicle.init();
	window.parent.global.ajaxLoading.close(1000);
});
var Vehicle = {
	init: function(){
		Vehicle.chooses ="";
		Vehicle.sub_url ="";
		Vehicle.queryW();
		Vehicle.tbTerminalParamsLoad = false;
		Vehicle.initEvent();
		Vehicle.initEnterprise();
		Vehicle.initVehicleSelect();
		this.initVehicleList();
	},
	queryW : function(){
		var winW = $('body').width();
		$('.querys').width(winW);
	},
	DriverReload: function(){
		Vehicle.queryVeicle();
	},
	initEvent: function(){
		
		$("#queryBtn").click(function(){
			Vehicle.queryVeicle();
		});
		
		$("#addVehicleBtn").click(function(){
			var url = appCtx + "/base/PubDriver/toaddPubDriver.html";
			window.parent.doDataDialog("insert","增加从业人员",iFrameName,"VehicleForm.saveDriver()","Vehicle.DriverReload()",url);
		});
		
		$("a[name='updateVehicleBtn']").click(function(){
			/*var id = $("#tbVehicles").getCheckedRows();
			var url = appCtx + "/base/PubDriver/toaddPubDriver.html?id="+id;
			window.parent.doDataDialog("update","修改从业人员",iFrameName,"VehicleForm.saveDriver()","Vehicle.DriverReload()",url);*/
			Vehicle.updateVehicle();
		});
		
		$("a[name='delVehicleBtn']").click(function(){
			Vehicle.delVehicles();
		});
		
		$("a[name='exportVehicleBtn']").click(function(){
			Vehicle.exportVehicle();
		});
		
		$("a[name='sync']").click(function(){
			Vehicle.synDriver();
		});
		
	},
	initVehicleSelect: function(){
		$("#Vehicle").select2({
	        theme: "default",
	        allowClear: true,
	        ajax:{
	            url:appCtx + "/base/PubDriver/selectVehicleList.html",
	            dataType:"json",
	            delay:250,
	            data:function(params){
	            	var enterprise = $('#enterprise').val();
	            	if (isNaN(enterprise)||enterprise==" ") {
	            		enterprise="";
					}
	                return {
	                	enterprise_id:enterprise,
	                	vehicle_no: params.term,
	                    page: params.page || 1
	                };
	            },
	            cache:true,
	            processResults: function (res, params) {
			    	if(res){
			    		var options = [];
			    		var option = {"id":" ", "text":"全部车辆"};
			    		options.push(option);
	    				$.each(res,function(index,obj) {
	    					var option = {"id":obj.vehicle_no, "text":obj.vehicle_no};
    	                    options.push(option);
	    				});
    	                return {
    	                	results: options,
    	                    pagination: {
    	                        more:false
    	                    }
    	                };
			    	}
	            },
	            escapeMarkup: function (markup) { return markup; },
	            minimumInputLength: 1
	        }
	    });
	},
	initEnterprise: function(){
		$('#enterprise').select2({
    		theme: "default",
 	        allowClear: true,
 	        placeholder: "全部业户",
 	        ajax:{
 	            url:appCtx + "/report/alarmSyn/queryEntAndPlatByRole.html?time="+ new Date().getTime(),
 	            dataType:"json",
 	            delay:250,
 	           async : true,
 	            data:function(params){
 	                return {
 	                    name: params.term,
 	                    page: params.page || 1
 	                };
 	            },
 	            cache:true,
 	            processResults: function (res, params) {
 	          
 			    	if(res){
 			    		var options = [];
 			    		var option = {"id":" ", "text":"全部业户"};
 			    		options.push(option);
 	    				$.each(res,function(index,obj) {
 	    					var option = {"id":obj.entId, "text":obj.entName};
     	                    options.push(option);
 	    				});
     	                return {
     	                	results: options,
     	                    pagination: {
     	                        more:false
     	                    }
     	                };
 			    	}
 	            },
 	            escapeMarkup: function (markup) { return markup; },
 	            minimumInputLength: 1
 	        }
    	});
	},
	
	queryVeicle: function(){
		var name = $("#name").val();
		var licence = $("#licence").val();
		var vehicle_id = $("#Vehicle").val();
		var enterprise_id = $("#enterprise").val(); 
		// 查询参数
		var params = [{
			name : 'name',
			value : name
		},{
			name : 'licence',
			value : licence
		},{
			name : 'vehicle_id',
			value : $.trim(vehicle_id)
		},{
			name : 'enterprise_id',
			value : $.trim(enterprise_id)
		}];
		$("#tbVehicles").flexOptions({
			url : appCtx + "base/PubDriver/queryPubDriver.html",
			newp : 1,// 设置起始页
			params : params
		// 设置查询参数
		}).flexReload();// 重新加载
	},
	getColumn: function(){
		return [{
			display : 'id',
			name : 'id',
			showTitle:true,
			hide:true,
		},{
			display : '从业人员姓名',
			name : 'name',
			width : 84,
			showTitle:true,
			sortable : false,
			align : 'left',
		},{
			display : '所属业户',
			name : 'enprise_name',
			width : 220,
			sortable : false,
			showTitle:true,
			align : 'left',
		},{
			display : '身份证号',
			name : 'id_card',
			width : 200,
			sortable : false,
			showTitle:true,
			align : 'left',
		},{
			display : '驾驶证',
			name : 'driver_licence',
			width : 200,
			sortable : false,
			showTitle:true,
			align : 'left',
		},{
			display : '驾驶类型',
			name : 'drive_type',
			width : 66,
			sortable : false,
			showTitle:true,
			align : 'left',
			paramcolnames:["drive_type"],
            handlefunction:function(drive_type){
            	var str = '';
            	if(drive_type==1){
            		str ='客运';
            	}else if(drive_type==2){
            		str='危险品';
            	}
            	else if(drive_type==3){
            		str='货运车';
            	}
        		return str;
            }
		},{
			display : '车牌号码',
			name : 'vehicle_no',
			width : 150,
			sortable : true,
			showTitle:true,
			align : 'left'
		},{
			display : '发证机关',
			name : 'lssuing_auth_name',
			width : 200,
			sortable : true,
			showTitle:true,
			align : 'left'
		},{
			display : '从业资格证号',
			name : 'licence',
			width : 220,
			sortable : true,
			showTitle:true,
			align : 'left'
		},{
			display : '资格证初领时间',
			name : 'acquire_time',
			width : 122,
			sortable : true,
			showTitle:true,
			align : 'left',
            paramcolnames:["acquire_time"],
            handlefunction:function(leave_time){
            	if (leave_time) {
            		return global.getTime(new Date(Number(leave_time)));
				}else{
					return "";
				}
            }
		},{
			display : '资格证发证时间',
			name : 'invalid_start_time',
			width : 122,
			sortable : true,
			showTitle:true,
			align : 'left',
            paramcolnames:["invalid_start_time"],
            handlefunction:function(leave_time){
            	if (leave_time) {
            		return global.getTime(new Date(Number(leave_time)));
				}else{
					return "";
				}
            }
		},{
			display : '资格证有效期',
			name : 'invalid_end_time',
			width : 122,
			sortable : true,
			showTitle:true,
			align : 'left',
            paramcolnames:["invalid_end_time"],
            handlefunction:function(leave_time){
            	if (leave_time) {
            		return global.getTime(new Date(Number(leave_time)));
				}else{
					return "";
				}
            }
		},{
			display : '证照状态',
			name : 'status',
			width : 63,
			sortable : true,
			showTitle:true,
			align : 'left',
            paramcolnames:["status"],
        
            handlefunction:function(status){
            	var str = '注销';
            	if(status==10){
            		str ='从业';
            	}else if(status==20){
            		str='行业';
            	}
        		return str;
            }
		},{
			display : '联系号码',
			name : 'phone',
			width : 90,
			sortable : true,
			showTitle:true,
			align : 'center'
		},{
			display : '短信提醒',
			name : 'enable_sms',
			width : 66,
			sortable : true,
			showTitle:true,
			align : 'left',
            paramcolnames:["enable_sms"],
            handlefunction:function(enable_sms){
            	var str;
            	if(enable_sms==1){
            		str ='启用';
            	}else{
            		str ='停用';
            	}
        		return str;
            }
		},{
			display : '照片',
			name : 'img_url',
			width : 40,
			sortable : true,
			showTitle:false,
			align : 'left',
			paramcolnames:["img_url","name"],
            handlefunction:function(img_url,name){
            	var str='<a href="javascript:;" onclick="showphoto(\''+img_url+'\',\''+name+'\')" >查看</a>';

        		return str;
            }
		},{
			display : '同步运政',
			name : 'has_sync',
			width : 60,
			sortable : true,
			showTitle:true,
			align : 'left',
			paramcolnames:["has_sync"],
            handlefunction:function(has_sync){
            	var str='已同步';
            	if(has_sync==0){
            		str='未同步';
            	}

        		return str;
            }
		 }];
	},
	initVehicleList: function(){
		var url = appCtx + "base/PubDriver/queryPubDriver.html";
		if(licence!=null||licence!=''){
			url=appCtx + "base/PubDriver/queryPubDriver.html?licence="+licence;
		}
		//var me = this;
		$("#tbVehicles").flexigrid({
			url :url ,
			dataType : 'json',
			colModel : Vehicle.getColumn(),
			resizable : false,
			sortname : "id",// 第一次加载数据时排序列
			sortorder : "desc",// 第一次加载数据时排序类型
			usepager : true,// 是否分页，默认为true。
			showToggleBtn : false,
			showTableToggleBtn : true,// 是否显示收起/打开按钮,默认不显示。
			useRp : true,// 是否可以动态设置每页显示的结果数，默认为false。
			rp : 10,// 每页记录数，默认为10
			checkbox : true,// 是否要多选框,默认为false。
            width:'auto',
			// width: $('#tdiv').width(),// 表格宽度
           // widthType : '%',
			rowId : 'id',// 多选框绑定行的id,只有checkbox : true时才有效。
			singleSelect : false,
			height : nav.whiceH[0] -157,
			
		// 表格高度
		});
	},
	updateVehicle: function(){
		//var me = this;
		var checkedIds = $("#tbVehicles").getCheckedRows();
		if(checkedIds.length<1){
			//window.parent.showVelidateModal("请选择要修改的数据！");
			window.parent.global.ajaxLoading.pop('请选择要修改的数据!',false,3000);
			return;
		}
		if(checkedIds.length>1){
			//window.parent.showVelidateModal("只能选择一条数据！");
			window.parent.global.ajaxLoading.pop('只能选择一条数据!',false,3000);
			return;
		}
		
		var url = appCtx + "base/PubDriver/toaddPubDriver.html?id="+checkedIds[0];
		//window.parent.doDataDialog("update","修改从业人员信息",iFrameName,"VehicleForm.saveVehicle()","Vehicle.DriverReload()",url);
		window.parent.doDataDialog("update","修改从业人员",iFrameName,"VehicleForm.saveDriver()","Vehicle.DriverReload()",url);
	},
	synDriver: function(){
		//var me = this;
		var checkedIds = $("#tbVehicles").getCheckedRows();
		if(checkedIds.length<1){
			window.parent.global.ajaxLoading.pop('请选择要修改的数据!',false,3000);
			return;
		}
		if(checkedIds.length>1){
			window.parent.global.ajaxLoading.pop('只能选择一条数据!',false,3000);
			return;
		}
		window.parent.doConfirm("确定要同步运政从业人员数据吗?",iFrameName,"Vehicle.synDataDriverConfirm()");
	},
	synDataDriverConfirm :function(){
		var checkedIds = $("#tbVehicles").getCheckedRows();
		$.ajax({
	        type: 'post',
	        async: false,
	        url: appCtx + "base/PubDriver/synDriverInfo.html",
			data:{
					vehicleIds : checkedIds.toString()
				 },
	        cache: false,
	        dataType : "JSON",
	        success: function (data) {
	        	var msg = "";
				if(data.code == "0"){
					$("#tbVehicles").flexReload();
					window.parent.global.ajaxLoading.pop('同步成功！',false,1000);
					return;
				}else if(data.code == "1"){
					window.parent.global.ajaxLoading.pop('运政无数据！',false,1000);
				}else{
					window.parent.global.ajaxLoading.pop('同步失败！',false,1000);
					
				}
				
	        }
	    });	
	},
	delVehicles: function(){
		//var me = this;
		var checkedIds = $("#tbVehicles").getCheckedRows();
		if(checkedIds.length<1){
			//window.parent.showVelidateModal("请选择要删除的数据！");
			window.parent.global.ajaxLoading.pop('请选择要删除的数据!',false,3000);
			return;
		}
		window.parent.doConfirm("确定要删除吗？删除后将无法恢复！",iFrameName,"Vehicle.deleteVehicleConfirm()");
		
	},
	deleteVehicleConfirm: function(){
		var checkedIds = $("#tbVehicles").getCheckedRows();
		$.ajax({
	        type: 'post',
	        async: false,
	        url: appCtx + "base/PubDriver/deleteDriver.html",
			data:{"id" : checkedIds.toString()},
	        cache: false,
	        dataType : "JSON",
	        success: function (data) {
	        	var msg = "";
				if(data.code == "0"){
					$("#tbVehicles").flexReload();
					window.parent.global.ajaxLoading.pop('删除成功！',false,1000);
					return;
				}else if(data.code == "1"){
					window.parent.global.ajaxLoading.pop('删除失败！',false,1000);
				}
				$("#validateContentText").html(msg);
				$("#velidateModal").modal("show");
	        }
	    });	
	},
exportComfirm:function(){

		var me = this;
		var p=window.parent;
		
		var options = $("#tbVehicles").getOptions();
		//总记录数
		var total = options.total;
		//开始页数
		var StartPage=window.parent.$("#StartPageIndex").val();
		//结束页数
		var EndPage=window.parent.$("#EndPageIndex").val();
		var validate=true;
		var msg="";
		if(!StartPage || StartPage==0){
			msg+="起始页不能为空或者0";
			validate=false;
		}
		if(!EndPage || EndPage==0){
			msg+="结束页不能为空或者0";
			validate=false;
		}
		
		if(StartPage && EndPage &&EndPage<StartPage){
			msg+="结束页要大于起始页";
			validate=false;
		}
		if(!validate){
			p.ajaxLoading(msg,false,2000);
			return;
		}
		p.$('#exportModal').modal('hide');
		p.ajaxLoading("正在导出,请稍后.....",true,2000);
		//每页大小
		var pagesize = options.rp;
		
		//获取导出的参数
		var exportParams = options.exportParams;
		if((EndPage - StartPage + 1) * pagesize > 60000&&total>60000)
		{
			global.ajaxLoading.pop("最多只能导出60000条数据", true, 2000);
			return
		}
		
        var column = Vehicle.getColumn();
        var getColumnW = $("#tdiv").width()+500;
        var exportColumns = new Array();
        for(var i=0;i<column.length;i++){
        	if(column[i].hide!=true &&column[i].name !="operation" && column[i].name !="noColor" && column[i].name !="registrationNoKindName"){
        		column[i].width = parseInt(getColumnW / 1000 * column[i].width);
        		exportColumns.push(column[i]);
        	}
        }
		var header1 = JSON.stringify(exportColumns);
		var colModelList=new Array();//表头
		colModelList.push(header1);
		var colModel= $.toJSON(colModelList);
		var registrationno = $("#registrationno").val();
		var name = $("#name").val();
		var licence = $("#licence").val();
		if(licence==null||licence==''){
			licence = licence;
		}
		var vehicle_id = $("#Vehicle").val();
		var enterprise = $("#enterprise").val(); 
		var contacts = $("#contacts").val(); 
		var paramsGrid =  {
				colModel:colModel,
				registrationno:registrationno,
				title:"从业人员信息",
				name:name,
				licence:licence,
				vehicle_id:$.trim(vehicle_id),
				enterprise_id:$.trim(enterprise),
				licence:licence,
				imgsrc:null,
				StartPage:StartPage,
				EndPage:EndPage,
				pagesize:pagesize
		};
		post(appCtx + "/base/PubDriver/exportDriver.html",paramsGrid);
	},
	/**
	 * 导出运政机构数据
	 */
	exportVehicle: function(){
		var p=window.parent;
		var options = $("#tbVehicles").getOptions();
		var total = options.total;
		if(total==0){
			p.ajaxLoading("无导出数据",false,1000);
			return;
		}
		var pages = options.pages;
		//设置默认的开始结束页
		window.parent.$("#StartPageIndex").val(1);
		window.parent.$("#EndPageIndex").val(pages);
		window.parent.doExportModal("导出从业人员信息",iFrameName,"Vehicle.exportComfirm()");   
		
	},
	contains: function(valArrays,val){
		for(var i = 0;i < valArrays.length;i++){
			if(valArrays[i] == val){
				return true;
			}
		}
		return false;
	}

};
function showphoto(url,name){
		window.parent.$("#photo").modal('show');
		window.parent.$("#tit").text('司机照片');
		window.parent.$("#imgurl").html("<img src=\""+imgPath+url+"\" style='display:block;margin:0 auto;width:200px;height:200px' alt='"+name+"'/>");
}
